package com.taiji.web.controller.workOrder;

import com.alibaba.fastjson2.JSONObject;
import com.taiji.common.utils.SecurityUtils;
import com.taiji.workOrder.mapper.UserProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


/**
 * @author a22999
 * @since 2023/06/29 18:32
 * description:
 */
@Component
public class CheckController extends OncePerRequestFilter {


    @Autowired
    private UserProjectMapper userProjectMapper;

    private int check(String projectCode){

        String userName = SecurityUtils.getLoginUser().getUser().getUserName();

        return userProjectMapper.selectHasUserProjectByProjectCodeAndUserName(projectCode, userName);

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String uri = request.getRequestURI();
        String[] uris={"/workOrder"};
        for (String s : uris) {
            if (!uri.startsWith(s)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        Map<String, String[]> parameterMap = request.getParameterMap();

        String[] strings = parameterMap.get("projectCode");
        if (strings != null && strings.length > 0){

            String projectCode = strings[0];
            int check = check(projectCode);
            if (check <= 0) {
                JSONObject obj = new JSONObject();
                obj.put("code",500);
                obj.put("msg", "没有该项目访问权限");
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(obj.toString());
                writer.flush();
                writer.close();
                return;
            }

        }

        filterChain.doFilter(request, response);

    }
}
